package com.leeyu.controller;

import com.leeyu.client.*;
import com.leeyu.rabbitmq.config.RabbitMQConfig;
import com.leeyu.util.GlobalCache;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class OrderPlaceController {

    @Autowired
    private ItemStockClient itemStockClient;

    @Autowired
    private OrderManageClient orderManageClient;

    @Autowired
    private CouponClient couponClient;

    @Autowired
    private UserPointsClient userPointsClient;

    @Autowired
    private BusinessClient businessClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 模拟用户下单操作
     * @return
     */
    @RequestMapping("/po")
    public String placeOrder(){
        long start = System.currentTimeMillis();
        // 1.调用库存服务扣除商品库存
        itemStockClient.decrItemStock();

        // 2.调用订单服务，创建订单
        orderManageClient.createOrder();

        // 使用RabbitMQ实现异步调用
        // 3.调用优惠券服务，预扣除优惠券
        //couponClient.deductCoupon();

        // 4.调用用户积分服务，预扣除用户使用的积分
        //userPointsClient.deductUserPoints();

        // 5.调用商家服务，通知商家用户已下单
        //businessClient.createOrderNotify();

        // 发送下单消息
        String correlationId = UUID.randomUUID().toString().replaceAll("-", "");
        // 重复消费测试
        //String correlationId = "f48ecea0604c4ea9901485b52769b21c";
        String message = "创建订单！";
        Map<String, Object> orderInfo = new HashMap<>();
        orderInfo.put("correlationId", correlationId);
        orderInfo.put("message", message);
        orderInfo.put("exchange", RabbitMQConfig.ORDER_PLACE_EXCHANGE);
        orderInfo.put("routingKey", "");
        orderInfo.put("sendTime", new Date());

        GlobalCache.set(correlationId, orderInfo);
        rabbitTemplate.convertAndSend(RabbitMQConfig.ORDER_PLACE_EXCHANGE,"", orderInfo, new CorrelationData(correlationId));

        long end = System.currentTimeMillis();
        return "success place order! cost: " + (end - start) + "ms";
    }
}
